﻿using Business.Solr;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Business {
    public class ResumeRepo {
        private readonly SolrClient _SolrClient;

        public ResumeRepo(SolrClient solrClient) {
            _SolrClient = solrClient;
        }

        public bool IsNotExistsMessage(string messageId) {
            var query = new SolrQuery();
            query.AddFq("MessageId", messageId);
            var result = _SolrClient.Query<Resume>(query);
            return result.Docs.NumFound == 0;
        }

        public SolrResponse<Resume> Query(string q, IDictionary<string, string> filters) {
            var query = new SolrQuery();
            query.Q = q;
            query.Facet = new SolrQueryFacet {
                Fields = new[] { "Position", "Gender", "BirthYear", "Marriage", "YearsOfWorking", "HuKou", "Education", "Salary" }
            };
            query.AddFq(filters);
            query.Rows = 100;
            query.ReturnFields = Resume.GetAllPropertiesWithoutBody();
                
            return _SolrClient.Query<Resume>(query);
        }

        public string GetBodyByPhoneNumber(string phoneNumber, string q) {
            var query = new SolrQuery();
            query.AddFq("PhoneNumber", phoneNumber);
            if (!string.IsNullOrWhiteSpace(q)){
                // 查询单个文档并指定查询关键字，启用高亮显示
                query.Highlighting = new SolrQueryHighlighting {
                    Query = q,
                    Fields = new []{"HtmlBody"}
                };
            }
            query.Rows = 1;
            var response = _SolrClient.Query<Resume>(query);

            // 如果有返回高亮正文，优先使用它
            if (response.Highlighting != null &&
                response.Highlighting.FirstOrDefault().Value != null &&
                response.Highlighting.FirstOrDefault().Value.FirstOrDefault().Value != null &&
                response.Highlighting.FirstOrDefault().Value.FirstOrDefault().Value.Length > 0) {
                var highlightingBody = response.Highlighting.FirstOrDefault().Value.FirstOrDefault().Value[0];
                if (!string.IsNullOrWhiteSpace(highlightingBody))
                    return highlightingBody;
            }

            // 否则使用body字段
            var resume = response.Docs.Docs.FirstOrDefault();
            if (resume != null)
                return resume.HtmlBody;

            return null;
        }
    }
}
